package top.csy8888.work01.websocket;

import com.google.gson.Gson;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import top.csy8888.work01.entity.Chat;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author CSY
 * @date 2025 - 09 - 18
 */
@ServerEndpoint(value = "/chat",configurator = HandshakeHandler.class)
public class ChatServer {
    private static final Map<String, Session> sessions = new HashMap<>();
    private static final List<Chat> chats = new ArrayList<>();

    @OnOpen
    public void onOpen(Session session) {
        String user = (String) session.getUserProperties().get("user");
        sessions.put(user, session);
        sendAllUsers(String.valueOf(sessions.size()));
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        String user = (String) session.getUserProperties().get("user");
        Chat chat = new Chat();
        chat.setUsername(user);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String format = sdf.format(new Date());
        chat.setMessage(message);
        chat.setTime(format);
        chats.add(chat);
        Gson gson = new Gson();
        String json = gson.toJson(chat);
        sendAllUsers(json);
    }

    public void sendAllUsers(String message) {
        sessions.forEach((key,value) ->{
            try {
                value.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @OnClose
    public void onClose(Session session) {
        String user = (String) session.getUserProperties().get("user");
        sessions.remove(user);
        sendAllUsers(String.valueOf(sessions.size()));
    }
}
